import statistics
import time
import os
import threading
from solox.public.apm import AppPerformanceMonitor
from solox.public.apm import initPerformanceService
from Common.connect_to_device import *
from Common.handle_log import do_log
from Common.basepage import BasePage

do_basepage = BasePage(device="d_one")
def get_cmd_command():
    x, y = [d_one.info["displaySizeDpX"], d_one.info["displaySizeDpY"]]
    cmd = f"adb shell input swipe {int(x/2)} {int(y/2+300)} {int(x/2)} {int(y/2-300)}  8000"
    do_log.info(cmd)
    return cmd



def click_iqi(cmd):
    do_basepage.close_IQIYI_app()
    time.sleep(2)
    do_basepage.start_IQIYI_app()
    time.sleep(4)
    global start_flag
    i = 1
    while i < 150 and start_flag:
        # cmd = "adb shell input swipe 700 700 700 100 8000"
        os.popen(cmd)
        do_log.info(f"执行向下滑动程序第{i}次")
        time.sleep(11)
        i += 1

def time_statistics(time_list, x):
    """
    求一组数据(一般是时间)的初值、最小、最大、平均、中位数、众数
    :param x: 保留的小数位数
    :param time_list: num list
    """
    first = time_list[0]
    min_time = min(time_list)
    max_time = max(time_list)
    avg = statistics.mean(time_list)
    median = statistics.median(time_list)
    getmode = statistics.mode(time_list)
    result = {'first': round(first, x),
              'min': round(min_time, x),
              'max': round(max_time, x),
              'avg': round(avg, x),
              'median': round(median, x),  # median 中位数
              'Mode': round(getmode, x)}  # Mode   众数
    return result

def get_fps(pkgName,device_id,during):
    """获取设备fps数据"""
    fps_list = []
    do_log.info("获取fps监控程序启动")
    apm = AppPerformanceMonitor(pkgName=pkgName, platform='Android', deviceId=device_id,
                            surfaceview=True, noLog=False, pid=None, record=False, collect_all=True, duration=1)
    time.sleep(10)
    for i in range(0, during):
        t1 = time.time()
        fps_one = float(apm.collectFps()["fps"])
        if fps_one>0:
            fps_list.append(fps_one)
        t2 = time.time()
        used_time = t2 - t1
        do_log.info(f"第{i+1}次获取的fps为:{fps_one},耗时:{used_time}")
        if used_time < 1.5:
            time.sleep(1.5 - used_time)
    time.sleep(3)

    res_fps = time_statistics(fps_list, 3)
    fmt = '{:^10}\t{:^8}\t{:^8}\t{:^8}\t{:^8}\t{:^8}'
    do_log.info(fmt.format('tyaction',"count",'first', 'min', 'max', 'avg', 'median', 'Mode'))
    do_log.info(fmt.format('FPS', len(fps_list),res_fps['first'], res_fps['min'], res_fps['max'], res_fps['avg'],
                     res_fps['median'], res_fps['Mode']))
    initPerformanceService.stop()



def start_monitoring(pkgName,device_id,during,cmd_command):
    # 启动函数A的线程 (click_iqi)
    global start_flag
    start_flag=True
    thread_A = threading.Thread(target=click_iqi,args=(cmd_command,))
    thread_A.start()
    time.sleep(10)
    # 启动监控函数B的线程 (get_fps)
    thread_B = threading.Thread(target=get_fps,args=(pkgName,device_id,during))
    thread_B.start()
    # 等待监控线程完成
    thread_B.join()
    start_flag = False
    # 等待点击函数A完成
    thread_A.join()
    print("Monitoring completed.")

if __name__ == '__main__':
    package_name='com.arcvideo.car.iqy.video'   #监控的应用名字
    device_1=None                  #adb devices设备id

    during=60 #采集次数
    cmd_command = "adb shell input swipe 700 700 700 100 8000"
    start_monitoring(package_name,device_1,during,cmd_command)

